package cn.edu.zut.hhr.controller;
import cn.edu.zut.hhr.entity.Dept;
import cn.edu.zut.hhr.mapper.DeptMapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired(required = false)
    private DiscoveryClient client;

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private DeptMapper deptMapper;


    @GetMapping("/{id}")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "getByIdHy")
    public Dept getById(@PathVariable("id") long id){
        Dept dept = deptMapper.getById(id);
        if(dept == null){
            throw new RuntimeException("id" + id + "不存在");
        }
        return dept;
    }

    public Dept getByIdHy(@PathVariable("id") long id){
        return new Dept("id: " + id + "不存在","null");
    }

    @GetMapping("/discovery")
    @ResponseBody
    public Object discovery(){
        List<ServiceInstance> list = client.getInstances(applicationName);
        System.out.println("discovery.info->: ");
        for(ServiceInstance si: list){
            System.out.println(
                    "host: " + si.getHost() + "\n"
                     + "instanceId: " + si.getInstanceId() + "\n"
            );
        }
        return list;
    }


}
